package ctrl.action.impl;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Model;
import model.beans.ShoppingCartBean;

import util.ProjectConstants;

import ctrl.action.ServletAction;

public class LogoutServletAction implements ServletAction{
	
	private ServletContext context;	
	public LogoutServletAction(ServletContext context) {
		this.context = context;
	}
	
	@Override
	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		
		String jsp;
		
		// retrieve model from context
		Model model = (Model) context.getAttribute(ProjectConstants.PARAMMODEL);
		
		HttpSession session = request.getSession();
		if(session.getAttribute(ProjectConstants.PARAMUSER) != null){
			session.setAttribute(ProjectConstants.PARAMUSER, null);			
			if(session.getAttribute(ProjectConstants.PARAMMYCART) != null){
				ShoppingCartBean cart = model.createShoppingCart();
				session.setAttribute(ProjectConstants.PARAMMYCART, cart);
			}
			
			request.setAttribute(ProjectConstants.PARAMLOGOUTMSG, "Welcome back! You are successfully logged off!");
		}
		else{
			request.setAttribute(ProjectConstants.PARAMLOGOUTMSG, "Sorry, You have not logged in!");
		}
		
		jsp = ProjectConstants.PAGELOGOUT;
		
		context.getRequestDispatcher("/" + jsp + ".jspx").forward(request, response);		
	}
}
